<template>
  <div class="baseband_control_container">
    <!-- AT指令卡片 -->
    <el-card>
      <template #header>
        <div class="flex items-center">
          <span>{{ t('functionService.at_command_label') }}</span>
        </div>
      </template>
      <div class="baseband-list-container" v-if="atCommandList.length">
        <div class="baseband-item" v-for="(item, index) in atCommandList" :key="item.id">
          <div class="baseband-header">
            <span class="m-r-10px">{{ item.name }}</span>
            <el-tag :type="item.version === 'Device not connected' ? 'danger' : 'success'" size="small">
              {{ t(`functionService.device_${item.version === 'Device not connected' ? 'not_connected' :
              'connected'}_label`) }}
            </el-tag>
          </div>          
          <div class="baseband-content">
            <!-- 左侧：输入框和快捷指令 -->
            <div class="left-panel">
              <div class="input-section">
                <div class="m-r-20px text-20px">{{ t('functionService.input_label') }}</div>
                <CustomSelect v-model="instructValues[index]" :options="instructList[index].options"
                  :placeholder="instructList[index].placeholder" :width="instructList[index].width" />
                <div class="global_btn m-l-20px" v-globalLoading="sendCommand.bind(null, item)" :class="{ 'is-loading': item.loading }">
                  <el-icon><Position /></el-icon>
                  {{ t('functionService.send_label') }}
                </div>
              </div>

              <div class="quick-commands-container">
                <div v-for="(quickItem, quickIndex) in item.quickList" :key="quickIndex"
                  class="global_btn m-r-10px m-b-10px"
                  v-globalLoading="handleSendQuickCommand.bind(null,item,quickItem)"
                  :class="{ 'is-loading': quickItem.loading }">
                  <span class="m-r-5px">{{ quickItem.description }}</span>
                  <span class="command">( {{ quickItem.inputValue }} )</span>
                  <el-icon class="delete-icon" @click.stop="handleQuickDelete(item)">
                    <Close />
                  </el-icon>
                </div>
              </div>
            </div>

            <!-- 右侧：日志内容 -->
            <div class="right-panel">
              <div class="log-header flex items-center justify-between">
                <span class="font-bold text-14px">{{ t('functionService.log_record_label') }}</span>
                <div class="global_btn" @click="handleClearLog(item)">{{ t('functionService.clear_log_label') }}</div>
              </div>
              <div class="log_container log_container_custom" :ref="el => { if(el) logContainers[item.id] = el }" style="padding-bottom: 50px;">
                <div class="log_item m-b-5px" v-for="(subItem, subIndex) in item.list" :key="subIndex">
                  <div v-for="(message, index) in subItem" :key="message" class="log-item">
                    <span class="log-index">[{{ index + 1 }}]</span>
                    <span :class="{
                      'log-content-command': message.type === 'command',
                      'log-content-message': message.type !== 'command',
                      'log-content': true
                    }">
                      {{ message.type === 'command' ? '>>>' : '<<<' }} {{ message.value }} </span>
                  </div>
                  <div class="m-t-10px"></div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 快捷指令管理卡片 -->
    <el-card class="m-t-20">
      <template #header>
        <div class="flex items-center">
          <!-- <el-icon class="m-r-10px"><Management /></el-icon> -->
          <span>{{ t('functionService.quick_command_manage_label') }}</span>
        </div>
      </template>
      <div class="w-50%">
        <div class="global_btn m-b-15px" @click="handleAddQuickCommand">
          <el-icon><Plus /></el-icon>
          {{ t('functionService.add_quick_command_label') }}
        </div>
        <el-table :data="quickList" max-height="200px">
          <el-table-column :label="t('functionService.command_description_label')" prop="description" />
          <el-table-column :label="t('functionService.quick_command_label')" prop="inputValue" />
          <el-table-column :label="t('functionService.operation_label')" >
            <template v-slot="{ row }">
              <div class="flex items-center">
                <div class="global_btn m-r-10px" @click="handleQuickEdit(row)">
                {{ t('functionService.quick_command_edit_label') }}
              </div>
              <div class="global_btn_cancel" @click="handleQuickDelete(row)">
                {{ t('functionService.quick_command_delete_label') }}
              </div>
              </div>           
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 基带状态卡片 -->
    <el-card class="m-t-20">
      <template #header>
        <div class="flex items-center">
          <el-icon class="m-r-10px">
            <Cpu />
          </el-icon>
          <span>{{ t('functionService.baseband_status_label') }}</span>
        </div>
      </template>
      <div class="m-b-20px flex items-center" v-if="basebandInfos.length > 1">
        <el-select v-model="currentBasebandId" class="select" placeholder="当前启用基带" size="large"
          popper-class="select_box">
          <template #label="{ label }">
            <span class="font-bold">{{ t('functionService.current_baseband_label') }}:{{ label }}</span>
          </template>
          <el-option v-for="item in basebandInfos" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
        <div class="global_btn m-l-20px" @click="handleChangeBool" :class="{ 'is-loading': isLoading }">
          <el-icon><Check /></el-icon>
          {{ t('functionService.confirm_label') }}
        </div>
      </div>
      <el-table :data="basebandInfos">
        <el-table-column :label="t('functionService.baseband_name_label')" prop="name" />
        <el-table-column :label="t('functionService.version_label')" prop="devinfo.version" />
        <el-table-column :label="t('functionService.network_status_label')" prop="status">
          <template v-slot="{ row }">
            <TagRender :value="row.status" name="networkStatus" />
          </template>
        </el-table-column>
        <el-table-column :label="t('functionService.network_ip_label')" prop="ip" />
        <el-table-column :label="t('functionService.track_label')" prop="devinfo.config">
          <template v-slot="{ row }">
            <TagRender :value="row.devinfo.config" name="orbit" />
          </template>
        </el-table-column>
        <el-table-column :label="t('functionService.use_status_label')" prop="bool">
          <template v-slot="{ row }">
            <TagRender :value="row.bool" name="bool" />
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <Dialog v-bind="basebandDiaLog" v-model:dialogVisible="basebandDiaLog.dialogVisible">
      <template #content>
        <div class="p-20px">
          <el-form ref="basebandFormRef" :model="basebandForm" :rules="baseBandFormRules" label-width="auto"
            label-position="left">
            <el-form-item :label="t('functionService.baseband_name_label')" prop="name">
              <el-input v-model="basebandForm.name" />
            </el-form-item>
            <el-form-item :label="t('functionService.track_label')" prop="orbit">
              <MSelect v-bind="trackConfig" v-model="basebandForm.orbit" />
            </el-form-item>
          </el-form>
          <div class="text-right m-t-30px">
            <!-- <el-button type="primary" @click="handleSaveBaseband">{{t('networkConfig.save_label')}}</el-button> -->
            <div class="global_btn_cancel" @click="basebandDiaLog.dialogVisible = false">
              {{ t('networkConfig.cancel_label') }}
            </div>
          </div>
        </div>
      </template>
    </Dialog>
    <Dialog v-bind="quickDiaLog" v-model:dialogVisible="quickDiaLog.dialogVisible">
      <template #content>
        <div class="p-20px">
          <el-form ref="quickFormRef" :model="quickForm" :rules="quickFormRules" label-width="auto"
            label-position="left">
            <el-form-item :label="t('functionService.command_description_label')" prop="description">
              <el-input v-model="quickForm.description" />
            </el-form-item>
            <el-form-item :label="t('functionService.quick_command_input_label')" prop="inputValue">
              <el-input v-model="quickForm.inputValue" />
            </el-form-item>
          </el-form>
          <div class="flex justify-end gap-20px m-t-30px">
            <div class="global_btn_cancel" @click="quickDiaLog.dialogVisible = false">
              {{ t('networkConfig.cancel_label') }}
            </div>
            <div class="global_btn" @click="handleSaveQuickCommand">
              {{ t('functionService.confirm_label') }}
            </div>
          </div>
        </div>
      </template>
    </Dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'
import {
  Monitor,
  Position,
  Lightning,
  Close,
  List,
  Management,
  Cpu,
  Plus,
  Check
} from '@element-plus/icons-vue'
export default defineComponent({
  name: 'BasebandControl',
})
</script>
<script setup lang="ts">
import { useI18n } from 'vue-i18n'
import { BasebandApi } from '@/api/basebandControl'
import { ElNotificationFn } from '@/utils/computedUtils'
import { ComponentPublicInstance } from 'vue'
const { t } = useI18n()
const atCommandList = ref<any>([])
const isLoading = ref(false)

const handleBlur = (val: string, index: number) => {
  if (!instructValues.value[index]) {
    instructValues.value[index] = ''
  }
  instructValues.value[index] = val
}

const sendCommand = async (item: any) => {
  const index = atCommandList.value.findIndex((i: any) => i.id === item.id)
  item.inputValue = instructValues.value[index] || ''
  if (!item.inputValue.trim()) {
    ElNotificationFn('warning', t('functionService.please_input_command_label'), '')
    return
  }
  item.loading = true
  try {
    const { data } = await BasebandApi.reqSendCommand({
      id: item.id,
      at: item.inputValue
    })
    const messages = data.message.split('\r\n').filter((item: any) => item.trim())
    const arr = [
      {
        type: 'command',
        value: item.inputValue
      },
      ...messages.map((item: any) => {
        return {
          type: 'message',
          value: item
        }
      })
    ]
    item.list.push(arr)
    item.inputValue = ''
  } finally {
    item.loading = false
  }
}

const currentBasebandId = ref<any>("")
const basebandInfos = ref<any>([])

const getBasebandInfo = async () => {
  const { data: { info } } = await BasebandApi.reqGetBasebandInfo()
  basebandInfos.value = info
  currentBasebandId.value = info.find((item: any) => item.bool)?.id
  if (atCommandList.value.length) return
  atCommandList.value = info.map((item: any) => {
    return {
      id: item.id,
      list: [],
      inputValue: '',
      name: item.name,
      version: item.devinfo.version,
      loading: false
    }
  })
}

async function handleChangeBool() {
  isLoading.value = true
  try {
    await BasebandApi.reqPostSwitchBaseband({
      id: currentBasebandId.value
    })
    ElNotificationFn('success', t('functionService.set_success_label'), '')
    getBasebandInfo()
  } finally {
    isLoading.value = false
  }
}

const basebandDiaLog = ref<any>({
  title: '',
  width: '500',
  dialogVisible: false,
  top: "35vh"
})

const trackConfig = computed<any>(() => ({
  options: [
    { label: t('functionService.high_orbit_label'), value: 'high' },
    { label: t('functionService.low_orbit_label'), value: 'low' },
  ],
  placeholder: t('functionService.track_label')
}))

const basebandForm = ref<any>({})
const basebandFormRef = ref<any>(null)
const baseBandFormRules = computed(() => {
  return {
    name: [{ required: true, message: t('functionService.baseband_name_label'), trigger: 'blur' }],
    orbit: [{ required: true, message: t('functionService.track_label'), trigger: 'blur' }],
  }
})

const quickList = ref<any>([])
const quickDiaLog = ref<any>({
  title: '',
  width: '500',
  dialogVisible: false,
  top: "35vh"
})

const quickForm = ref<any>({
  description: '',
  inputValue: ''
})

const quickFormRef = ref<any>(null)
const quickFormRules = computed(() => {
  return {
    description: [{ required: true, message: t('functionService.command_description_label'), trigger: 'blur' }],
    inputValue: [{ required: true, message: t('functionService.quick_command_input_label'), trigger: 'blur' }],
  }
})

function handleAddQuickCommand() {
  quickDiaLog.value.title = t('functionService.add_quick_command_label')
  quickForm.value = {
    description: '',
    inputValue: ''
  }
  quickDiaLog.value.dialogVisible = true
}

async function handleSaveQuickCommand() {
  await quickFormRef.value.validate()
  await BasebandApi.reqSaveQuickCommand({
    ...quickForm.value
  })
  ElNotificationFn('success', t('functionService.set_success_label'), '')
  getQuickCommand()
  quickDiaLog.value.dialogVisible = false
}

async function getQuickCommand() {
  const { data } = await BasebandApi.reqGetQuickCommand()
  quickList.value = data.quickList
  atCommandList.value = atCommandList.value.map((item: any) => {
    return {
      ...item,
      quickList: quickList.value.map((quickItem: any) => {
        return {
          ...quickItem,
          loading: false
        }
      })
    }
  })
}

function handleQuickEdit(row: any) {
  quickDiaLog.value.title = t('functionService.quick_command_edit_label')
  quickForm.value = { ...row }
  quickDiaLog.value.dialogVisible = true
}

async function handleQuickDelete(row: any) {
  await BasebandApi.reqDeleteQuickCommand({
    id: row.id
  })
  ElNotificationFn('success', t('functionService.delete_success_label'), '')
  getQuickCommand()
}

async function handleSendQuickCommand(item: any, quickItem: any) {
  quickItem.loading = true
  try {
    const { data } = await BasebandApi.reqSendCommand({
      id: item.id,
      at: quickItem.inputValue
    })
    const messages = data.message.split('\r\n').filter((item: any) => item.trim())
    const arr = [
      {
        type: 'command',
        value: quickItem.inputValue
      },
      ...messages.map((item: any) => {
        return {
          type: 'message',
          value: item
        }
      })
    ]
    item.list.push(arr)
    scrollToBottom(item.id)
  } finally {
    quickItem.loading = false
  }
}

const instructValues = ref<string[]>(['', ''])
const instructList = computed(() => {
  return atCommandList.value.map((_: any, index: number) => ({
    inputValue: instructValues.value[index],
    options: quickList.value.map((item: any) => ({
      label: `${item.description} (${item.inputValue})`,
      value: item.inputValue
    })),
    placeholder: t('functionService.add_quick_command_input_label'),
    filterable: true,
    remote: true,
    width: '50%'
  }))
})

function handleClearLog(item: any) {
  item.list = []
}

type LogContainerElement = HTMLElement | ComponentPublicInstance | null
const logContainers = ref<Record<string, any>>({})

function scrollToBottom(itemId: string) {
  nextTick(() => {
    const container = logContainers.value[itemId];
    if (container) {
      // 添加小延迟以确保DOM完全更新
      setTimeout(() => {
        container.scrollTop = container.scrollHeight;
      }, 10);
    }
  });
}

let basebandTimer: any = null
const clearBasebandTimer = () => {
  if (basebandTimer) {
    clearInterval(basebandTimer)
    basebandTimer = null
  }
}
const fetchTasks = [
  { fn: getBasebandInfo, name: '基带信息' },
  { fn: getQuickCommand, name: '快捷指令' }
]
async function init() {
  const results = await Promise.allSettled(
    fetchTasks.map(task => task.fn())
  )  
  results.forEach((result, index) => {
    if (result.status === 'rejected') {
      console.error(`获取${fetchTasks[index].name}失败:`, result.reason)
    }
  })
}
function scheduleNextUpdate() {
  basebandTimer = window.setTimeout(() => {
    init().finally(() => {
      if (basebandTimer) {
        scheduleNextUpdate()
      }
    })
  }, 3000)
}
onActivated(() => {
  init()
  scheduleNextUpdate()
})

onDeactivated(() => {
  if (basebandTimer) {
    clearTimeout(basebandTimer)
    basebandTimer = null
  }
})
onUnmounted(clearBasebandTimer)
</script>

<style lang="scss" scoped>
@import '@/styles/pageLabel.scss';
@import '@/styles/input.scss';
@import '@/styles/log_container.scss';
@import '@/styles/table.scss';
@import '@/styles/form.scss';
@import '@/styles/select.scss';
@import '@/styles/card.scss';
@import '@/styles/dialog.scss';
.baseband_control_container {
  padding: 20px;
}

.m-t-20 {
  margin-top: 20px;
}

.m-r-10px {
  margin-right: 10px;
}

.m-l-20px {
  margin-left: 20px;
}

.m-b-15px {
  margin-bottom: 15px;
}

.m-b-10px {
  margin-bottom: 10px;
}

:deep(.el-icon) {
  font-size: 18px;
}

.el-button {
  .el-icon {
    margin-right: 4px;
  }
}

.select {
  max-width: 400px;
}

// 基带列表容器
.baseband-list-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

// 基带项
.baseband-item {
  display: flex;
  flex-direction: column;
  border: 1px solid rgba(31, 106, 178, 0.2);
  border-radius: 8px;
  overflow: hidden;
  background: rgba(24, 95, 170, 0.05);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

// 基带头部
.baseband-header {
  display: flex;
  align-items: center;
  // background: linear-gradient(90deg, #004B94, #0a3c6c);
  padding: 10px 15px;
  color: white;
  font-weight: bold;
  font-size: 16px;
  position: relative;
  
  &::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 1px;
    background: linear-gradient(
      90deg,
      transparent 0%,
      rgba(0, 209, 237, 0.5) 50%,
      transparent 100%
    );
  }
}

// 基带内容区
.baseband-content {
  display: flex;
  gap: 20px;
  padding: 15px;
}

// 左侧面板
.left-panel {
  width: 45%;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

// 右侧面板
.right-panel {
  width: 55%;
  display: flex;
  flex-direction: column;
}

// 输入区域
.input-section {
  display: flex;
  align-items: center;
  padding: 10px;
  background: rgba(24, 95, 170, 0.1);
  border-radius: 6px;
  border: 1px solid rgba(31, 106, 178, 0.2);
}

// 日志头部
.log-header {
  margin-bottom: 10px;
  padding: 6px 10px;
  background: rgba(24, 95, 170, 0.1);
  border-radius: 6px;
  border: 1px solid rgba(31, 106, 178, 0.2);
}

// 优化快捷命令样式
.quick-commands-container {
  display: flex;
  flex-wrap: wrap;
  padding: 10px;
  background: rgba(24, 95, 170, 0.1);
  border-radius: 6px;
  border: 1px solid rgba(31, 106, 178, 0.2);
  position: relative;
  height: 100%;
  overflow-y: auto;
  box-shadow: inset 0 0 10px rgba(24, 95, 170, 0.05);
  color: #fff;

  
  // 强化命令按钮样式
  .global_btn {
    border: 1px solid rgba(56, 176, 213, 0.4) !important;
    background: linear-gradient(180deg, rgba(24, 95, 170, 0.2), rgba(24, 95, 170, 0.4)) !important;
    transition: all 0.2s ease !important;
    
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 3px 8px rgba(0, 0, 0, 0.1);
      background: linear-gradient(180deg, rgba(24, 95, 170, 0.3), rgba(24, 95, 170, 0.5)) !important;
    }
    
    .command {
      // font-family: monospace;
      font-weight: bold;   
    }  
    .delete-icon {
      opacity: 0.6;
      transition: all 0.2s;
      
      &:hover {
        opacity: 1;
        transform: scale(1.1);
      }
    }
  }
}

// 添加科技感动画
@keyframes pulse {
  0%, 100% {
    opacity: 0.8;
  }
  50% {
    opacity: 1;
  }
}

@keyframes border-flow {
  0% {
    background-position: 0% 0;
  }
  100% {
    background-position: 100% 0;
  }
}

// 优化日志容器
.log_container_custom {
  height: 300px;
  overflow-y: auto;
  background: rgba(8, 32, 58, 0.9); // 深色背景提高对比度
  border: 1px solid rgba(31, 106, 178, 0.3);
  border-radius: 6px;
  padding: 10px;
  box-shadow: inset 0 0 15px rgba(0, 0, 0, 0.2);
  
  .log-item {
    margin-bottom: 5px;
    
    .log-index {
      color: #38B0D5;
      font-weight: bold;
      margin-right: 5px;
    }
    
    .log-content-command {
      color: #5CCCF0;
      font-weight: bold;
    }
    
    .log-content-message {
      color: #E9E9E9; // 淡色文字在深色背景上更易读
    }
    
    .log-content {
      font-family: 'Courier New', monospace; // 等宽字体提高代码可读性
    }
  }
  
  &::-webkit-scrollbar {
    width: 6px;
  }
  
  &::-webkit-scrollbar-track {
    background: rgba(8, 32, 58, 0.5);
  }
  
  &::-webkit-scrollbar-thumb {
    background: #38B0D5;
    border-radius: 3px;
  }
}

@media (max-width: 1200px) {
  .baseband-content {
    flex-direction: column;
  }
  
  .left-panel, .right-panel {
    width: 100%;
  }
  
  .left-panel::before, .right-panel::before {
    position: static;
    display: block;
    margin-bottom: 10px;
  }
}
</style>
